﻿using IM.Easy.Core.AppContext;
using IM.Easy.Core.Options;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace IM.Easy.Api.OAuth
{
    /// <summary>
    /// 默认认证方式
    /// </summary>
    public static class DefaultAuthentication
    {
        /// <summary>
        /// 默认的方式为Jwt认证
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static AuthenticationBuilder AddDefaultAuthentication(this AuthenticationBuilder builder)
        {
            var jwtOptions = ImApp.Configuration.Get<JwtOptions>();
            return builder.AddJwtAuthentication();
        }

        public static AuthenticationBuilder AddJwtAuthentication(this AuthenticationBuilder builder)
        {
            var jwtOptions = ImApp.Configuration.Get<JwtOptions>();
            // 配置 JWT Bearer 认证
            builder
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = jwtOptions.ValidateIssuer,
                        ValidateAudience = jwtOptions.ValidateAudience,
                        ValidateLifetime = jwtOptions.ValidateLifetime,
                        ValidateIssuerSigningKey = jwtOptions.ValidateIssuerSigningKey,
                        ValidIssuer = jwtOptions.ValidIssuer,  // 替换为你的颁发者
                        ValidAudience = jwtOptions.ValidAudience, // 替换为你的受众
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.IssuerSigningKey)) // 替换为你的密钥
                    };
                    options.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = context =>
                        {
                            var accessToken = context.Request.Query["access_token"];
                            if (!string.IsNullOrEmpty(accessToken) &&
                                context.HttpContext.Request.Path.StartsWithSegments("/userHub"))
                            {
                                context.Token = accessToken;
                            }

                            return Task.CompletedTask;
                        }
                    };
                });
            return builder;
        }

    }
}
